//
//  JGJAddDataCell.swift
//  FootballDataRecord
//
//  Created by Xx Jiang on 2020/1/8.
//  Copyright © 2020 Xx Jiang. All rights reserved.
//

import UIKit

class JGJAddDataCell: UITableViewCell{
    @IBOutlet weak var leftStepper: UIStepper!
    @IBOutlet weak var leftCount: UILabel!
    @IBOutlet weak var rightStepper: UIStepper!
    @IBOutlet weak var rightCount: UILabel!
    var cellType:String!
    var indexInTableview:Int!
    var lastLeftValue:Int = 0  //用来记录上一个左边值
    var lastRightValue:Int = 0 //用来记录上一个右边值
    var clickedValue:Int = 0  //用来记录点击后的值
    var matchModel:MatchModel?
    var matchDataModelA:MatchDataModel?{
        didSet{
            leftCount.text = ((self.matchDataModelA?.value(forKey: matchDataKeyDic[self.cellType]!)  ?? "0" ) as! String)
            lastLeftValue = Int(leftCount.text!)!
            self.leftStepper.value = Double(Int(leftCount.text!)!)
        }
    }
    var matchDataModelB:MatchDataModel?{
        didSet{
                 rightCount.text = ((self.matchDataModelB?.value(forKey: matchDataKeyDic[self.cellType]!)  ?? "0" ) as! String)
            lastRightValue = Int(rightCount.text!)!
            self.rightStepper.value = Double(Int(rightCount.text!)!)

               }
        
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        NotificationCenter.default.addObserver(self, selector: #selector(noticeAciton(notice:)), name: NSNotification.Name(rawValue: "changeCount"), object: nil)

    }
    
    
    @objc func noticeAciton(notice:NSNotification){
        if (notice.userInfo!["indexInTableview"] as! Int) != indexInTableview!{
                   return
               }
        
        let model:PlayerModel = notice.object as! PlayerModel
                   
                   var value:String?
                   //接收选择完后的通知并改变相应的数值（是左还是又）
                   var teamModel:TeamModel?
                   if (notice.userInfo!["team"] as! AddGameDetailViewController.TeamType) == AddGameDetailViewController.TeamType.leftTeam{
                       self.lastLeftValue = Int(self.clickedValue)
                       self.leftStepper.value = Double(self.clickedValue)
                       self.leftCount.text = "\(Int(self.clickedValue))"
                       value = self.leftCount.text
                       teamModel = TeamModel.getTeamModelWithTeamID(teamId: self.matchModel!.matchTeamA!)
                       if self.cellType == "进球"{
                           self.matchModel?.matchScoreA = value
                           DHDataBaseOperate.changeValuesWithModel(model: self.matchModel!, keys: ["mainKey":DHMatchId,"valueKey":DHMatchScoreA]) { (rs) in
                           }
                       }
                       //修改数据库
                   }else{
                       self.lastRightValue = Int(self.clickedValue)
                       self.rightStepper.value = Double(self.clickedValue)
                       self.rightCount.text = "\(Int(self.clickedValue))"
                       
                       value = self.rightCount.text
                       teamModel = TeamModel.getTeamModelWithTeamID(teamId: self.matchModel!.matchTeamB!)
                       
                       if self.cellType == "进球"{
                           self.matchModel?.matchScoreB = value
                           DHDataBaseOperate.changeValuesWithModel(model: self.matchModel!, keys: ["mainKey":DHMatchId,"valueKey":DHMatchScoreB]) { (rs) in
                           }
                       }
                       //修改数据库
                   }
        
        changeMatchdata(value: value!, model: model)
        changeMatchdata(value: value!, model: teamModel!)
    }
    
    func changeMatchdata(value:String,model:AnyObject){
        var matchDataID:String?
        if  model is TeamModel {
            let teamModel = model as! TeamModel
            if DYStringIsEmpty(value: teamModel.teamID as AnyObject) {
                return
            }
            matchDataID = "\(matchModel?.matchId ?? "")_team_\(teamModel.teamID ?? "")"
        }else{
            let player = model as! PlayerModel
            if DYStringIsEmpty(value: player.playerID as AnyObject?){
                return
            }
            matchDataID = "\(matchModel?.matchId ?? "")_player_\(player.playerID ?? "")"
        }
        
        MatchDataModel.getMatchDataModelWithID(matchDataID:matchDataID!) { (rs) in
            if rs is MatchDataModel{
                DispatchQueue.main.async {
                    let model = rs as! MatchDataModel
                    model.setValue(value, forKey: matchDataKeyDic[self.cellType]!)
                    DHDataBaseOperate.changeValuesWithModel(model: model, keys: ["mainKey":DHMatchDataID,"valueKey":matchDataKeyDic[self.cellType] as Any]) { (rs) in
                        if rs.isEqual(1)
                        {
                            print("插入成功")
                        }else{
                            
                        }
                    }
                }
            }else{
                print("查询失败")
            }
        }
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
    }
    @IBAction func clickLeftStepper(_ sender: Any) {
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "leftTeamAlertPickerView"), object: nil,userInfo: ["post":cellType as Any,"indexInTableview":indexInTableview as Any])
        //Bug 点击完stepper后他的value 就变了。  ---》 可我们要的结果是在选择ok后再改变。
        //解决 下面
        //用变量记录当前值（若监听通知有改变则去改变）
        self.clickedValue = Int(self.leftStepper.value)
        //先不改变值（因为不确定接下来是否点击了取消）
        self.leftStepper.value = Double(self.lastLeftValue)  // 变为点击前的值
        
        
    }
    
    @IBAction func clickRightStepper(_ sender: Any) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "rightTeamAlertPickerView"), object: cellType,userInfo: ["post":cellType as Any,"indexInTableview":indexInTableview as Any])
        self.clickedValue = Int(self.rightStepper.value)
        self.rightStepper.value = Double(self.lastRightValue)
        
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
}
